package com.atguigu.tingshu.order.util;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2024-03-11 11:30
 */
@Slf4j
@Component
public class DelayMesageUtil {

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 基于Redisson实现延迟消息
     *
     * @param queueName 阻塞队列名称
     * @param data     消息内容
     * @param ttl      延迟时间
     * @param timeUnit 延迟时间单位
     */
    public void sendDelayMessage(String queueName, String data, int ttl, TimeUnit timeUnit) {
        try {
            //1.基于RedissonClient创建阻塞队列
            RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(queueName);
            //2.基于RedissonClient将阻塞队列作为参数场景延迟队列
            RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
            //3.调用延迟队列发送延迟消息
            delayedQueue.offer(data, ttl, timeUnit);
            log.info("延迟消息：{}，发送成功,延迟：{}秒", data, ttl);
        } catch (Exception e) {
            log.error("[延迟消息]发送延迟消息:{}异常", data);
            throw new RuntimeException(e);
        }
    }
}
